package com.ruoyi.system.service;

import com.getui.push.v2.sdk.ApiHelper;
import com.getui.push.v2.sdk.GtApiConfiguration;
import com.getui.push.v2.sdk.api.PushApi;
import com.getui.push.v2.sdk.common.ApiResult;
import com.getui.push.v2.sdk.dto.req.Audience;
import com.getui.push.v2.sdk.dto.req.message.PushDTO;
import com.getui.push.v2.sdk.dto.req.message.PushMessage;
import com.getui.push.v2.sdk.dto.req.message.android.GTNotification;
import com.ruoyi.common.config.GeTuiConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class GeTuiPushService {

    public PushApi pushApi;

    @Autowired
    public GeTuiPushService(GeTuiConfig geTuiConfig) {
        // 配置个推API
        GtApiConfiguration apiConfiguration = new GtApiConfiguration();
        apiConfiguration.setAppId(geTuiConfig.getAppId());
        apiConfiguration.setAppKey(geTuiConfig.getAppKey());
        apiConfiguration.setMasterSecret(geTuiConfig.getMasterSecret());
        apiConfiguration.setDomain("https://restapi.getui.com/v2/"); // 设置API地址

        ApiHelper apiHelper = ApiHelper.build(apiConfiguration);
        // 初始化PushApi
        this.pushApi = apiHelper.creatApi(PushApi.class);
    }

    /**
     * 发送推送到指定的CID
     */
    public void pushToSingle(String cid, String title, String body, String url) {
        // 创建推送消息
        PushDTO<Audience> pushDTO = new PushDTO<>();
        pushDTO.setRequestId(System.currentTimeMillis() + "");

        // 设置推送内容
        PushMessage pushMessage = new PushMessage();
        pushDTO.setPushMessage(pushMessage);

        GTNotification notification = new GTNotification();
        pushMessage.setNotification(notification);
        notification.setTitle(title);
        notification.setBody(body);
        notification.setClickType("url");
        notification.setUrl(url);

        // 设置接收用户
        Audience audience = new Audience();
        audience.addCid(cid);
        pushDTO.setAudience(audience);

        // 发送推送
        ApiResult<Map<String, Map<String, String>>> apiResult = pushApi.pushToSingleByCid(pushDTO);
        if (apiResult.isSuccess()) {
            System.out.println("推送成功：" + apiResult.getData());
        } else {
            System.out.println("推送失败，code: " + apiResult.getCode() + ", msg: " + apiResult.getMsg());
        }
    }
}
